import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

class DeviceShareNotifier
    extends AutoDisposeAsyncNotifier<List<ThingSmartShareMemberModel>> {
  @override
  Future<List<ThingSmartShareMemberModel>> build() async {
    return [];
  }

  Future<void> getMemberShareList({required String devId}) async {
    state = AsyncLoading();
    try {
      final newState = await TuyaService().getMemberShareList(devId: devId);
      state = AsyncValue.data(newState);
    } catch (e, st) {
      Log.e("getMemberShareList", e, st);
      state = AsyncValue.error(e, st);
    }
  }

  Future<bool> addMemberShare({
    required String devId,
    required String userAccount,
  }) async {
    try {
      final ret = await TuyaService().addShareDevice(
        userAccount: userAccount,
        devIdList: [devId],
      );
      return ret;
    } catch (e, st) {
      Log.e("getMemberShareList", e, st);
      return false;
    }
  }

  Future<bool> removeMemberShare({required int memberId}) async {
    try {
      final ret = await TuyaService().removeShareMember(memberId: memberId);
      if (ret) {
        state = state.whenData(
          (members) => members
              .where((element) => element.memberId != memberId)
              .toList(),
        );
      }
      return ret;
    } catch (e, st) {
      Log.e("removeMemberShare", e, st);
      return false;
    }
  }
}

final deviceMemberShareListNotifierProvider =
    AutoDisposeAsyncNotifierProvider<
      DeviceShareNotifier,
      List<ThingSmartShareMemberModel>
    >(() => DeviceShareNotifier());
